package com.googlecode.tracey.audit;

import com.googlecode.tracey.id.TraceyIdValue;
import org.apache.log4j.Level;

import static org.apache.log4j.Logger.getLogger;

public class Log4jMessageAuditor implements MessageAuditor {
    private final MessageFormatter messageFormatter;
    private final DefaultLoggerName defaultLoggerName;
    private final Level logLevel;


    public Log4jMessageAuditor(Clock clock, IdGenerator idGenerator, DefaultLoggerName defaultLoggerName) {
        this(clock, idGenerator, defaultLoggerName, Level.INFO);
    }

    public Log4jMessageAuditor(Clock clock, IdGenerator idGenerator, DefaultLoggerName defaultLoggerName, Level logLevel) {
        this.defaultLoggerName = defaultLoggerName;
        messageFormatter = new MessageFormatter(clock, idGenerator);
        this.logLevel = logLevel;
    }

    public void audit(TraceyIdValue traceyId, TraceyAuditMessage traceyAuditMessage) {
        auditToNamedLog(defaultLoggerName.value(), traceyId, traceyAuditMessage);
    }

    public void auditToNamedLog(String auditName, TraceyIdValue traceyId, TraceyAuditMessage traceyAuditMessage) {
        getLogger(auditName).log(logLevel, messageFormatter.formatMessage(traceyId, traceyAuditMessage));
    }

}
